package jdbc.lessen02.util;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @Package lessen02.util
 * @Author shimmer
 * @Date 2020/7/31 9:36
 * @TODO
 */
public class JdbcUtil {
    private static String url=null; 
    private static String userName=null; 
    private static String passWord=null; 
    static {
        try {
            // 默认读取classpath文件--resources目录
            InputStream in = JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            properties.load(in);

            String diver = properties.getProperty("diver");
            url = properties.getProperty("url");
            userName = properties.getProperty("userName");
            passWord = properties.getProperty("passWord");
            
            //加载驱动
            Class.forName(diver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    // 获取连接
    public static Connection getConnection() throws SQLException{
        return DriverManager.getConnection(url,userName,passWord);
    }
    
    //释放资源
    public static void release(ResultSet rs,Statement st, Connection con){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(st!=null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(con!=null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
